package com.fivefu.core.hillstone.services.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hillstone.dto.response.EquipmentInfoDto;
import com.fivefu.core.hillstone.entity.DbHillstoneDevice;
import com.fivefu.core.hillstone.mapper.DbHillstoneDeviceMapper;
import com.fivefu.core.hillstone.services.DbHillstoneDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.hillstone.services.HillstoneService;
import com.fivefu.module.dictionary.entity.DbSysDict;
import com.fivefu.module.dictionary.service.DbSysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 大华设备表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-08-23 15:31:32
 */
@Service
public class DbHillstoneDeviceServiceImpl extends ServiceImpl<DbHillstoneDeviceMapper, DbHillstoneDevice> implements DbHillstoneDeviceService {

    @Autowired
    private HillstoneService hillstoneService;

    @Autowired
    private DbSysDictService dbSysDictService;

    /**
     * 通过设备编码查询设备信息
     * @param deviceCode   设备编码
     * @return
     */
    public DbHillstoneDevice queryHillstoneDevice(String deviceCode) {
        QueryWrapper<DbHillstoneDevice> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("device_code",deviceCode);
        DbHillstoneDevice device = baseMapper.selectOne(wrapper);
        return device;
    }

    /**
     * 编辑设备信息
     * @param device
     */
    @Override
    public void editDbHillstoneDevice(DbHillstoneDevice device) {
        LocalDateTime time = LocalDateTime.now();
        DbHillstoneDevice oldDevice = queryHillstoneDevice(device.getDeviceCode());
        device.setUpdatedBy("sys");
        device.setUpdatedTime(time);

        //判断协议类型是否为空
        if (StrUtils.isNotNull(device.getProtocolType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("TTP", device.getProtocolType());
            if (null != dict) {
                device.setProtocolType(dict.getDictCode());
            }
        }
        //判断设备小类是否为空
        if (StrUtils.isNotNull(device.getSubType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("RT", device.getSubType());
            if (null != dict) {
                device.setSubType(dict.getDictCode());
            }
        }
        //判断厂商是否为空
        if (StrUtils.isNotNull(device.getDeviceManufacturer())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("MP", device.getDeviceManufacturer());
            if (null != dict) {
                device.setDeviceManufacturer(dict.getDictCode());
            }
        }
        //判断设备大类是否为空
        if (StrUtils.isNotNull(device.getDeviceType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("RT", device.getDeviceType());
            if (null != dict) {
                device.setDeviceType(dict.getDictCode());
            }
        }
        //判断添加类型是否为空
        if (StrUtils.isNotNull(device.getAddType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("TJLX", device.getAddType());
            if (null != dict) {
                device.setAddType(dict.getDictCode());
            }
        }
        //判断是否已经存在相关信息数据
        if (null != oldDevice) {
            device.setId(oldDevice.getId());
            baseMapper.updateById(device);
        } else {
            device.setCreatedBy("sys");
            device.setCreatedTime(time);
            device.setIsDelete(0);
            baseMapper.insert(device);
        }

    }

    /**
     * 获取设备节点信息
     */
    @Override
    public void queryEquipmentInfoByDeviceCode() {
        //查询本地设备表所有数据
        List<DbHillstoneDevice> deviceList = queryAllDevice();
        if (null != deviceList && deviceList.size() > 0) {
            for (DbHillstoneDevice hillstoneDevice : deviceList) {
                String result = hillstoneService.getHillstone("/videoService/devicesManager/devices/" + hillstoneDevice.getDeviceCode());
                if (StrUtils.isNotNull(result) && !result.equals("error")) {
                    EquipmentInfoDto equipmentInfoDto = JSON.parseObject(result,EquipmentInfoDto.class);
                    DbHillstoneDevice device = equipmentInfoDto.formartHillstoneDevice();
                    editDbHillstoneDevice(device);
                }
            }
        }
    }

    /**
     * 删除多余设备数据信息
     * @param deviceCode   设备唯一标识
     */
    @Override
    public void deleteRedundantData(String deviceCode) {
        LocalDateTime time = LocalDateTime.now();
        List<DbHillstoneDevice> deviceList = queryDeviceList(deviceCode);

        //判断是否已经存在相关数据信息
        if (null != deviceList && deviceList.size() > 0) {
            List<Long> idList = deviceList.stream().map(k -> k.getId()).collect(Collectors.toList());
            Map<String, Long> deviceMap = deviceList.stream().collect(Collectors.toMap(k -> k.getDeviceCode(), v -> v.getId()));
            if (StrUtils.isNotNull(deviceCode)) {
                if (deviceMap.containsKey(deviceCode)) {
                    Long id = deviceMap.get(deviceCode);
                    idList.remove(id);
                }
            }

            //删除多余设备数据
            if (idList.size() > 0) {
                DbHillstoneDevice device = new DbHillstoneDevice();
                device.setIsDelete(1);
                device.setUpdatedBy("sys");
                device.setUpdatedTime(time);

                QueryWrapper<DbHillstoneDevice> wrapper = new QueryWrapper<>();
                wrapper.in("id",idList);
                wrapper.eq("is_delete",0);
                wrapper.eq("device_code",deviceCode);
                baseMapper.update(device,wrapper);
            }
        }
    }

    /**
     * 根据设备唯一标识查询相关数据
     * @param deviceCode
     * @return
     */
    @Override
    public List<DbHillstoneDevice> queryDeviceList(String deviceCode) {
        QueryWrapper<DbHillstoneDevice> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("device_code",deviceCode);
        List<DbHillstoneDevice> devicesList = baseMapper.selectList(wrapper);
        return devicesList;
    }

    /**
     * 获取本地设备表所有数据
     * @return
     */
    @Override
    public List<DbHillstoneDevice> queryAllDevice() {
        QueryWrapper<DbHillstoneDevice> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<DbHillstoneDevice> devicesList = baseMapper.selectList(wrapper);
        return devicesList;
    }

    /**
     * 获取设备节点信息  汇总用
     */
    @Override
    public DbHillstoneDevice queryEquipmentInfoByDeviceCodeCollect(String deviceCode) {
        String result = hillstoneService.getHillstone("/videoService/devicesManager/devices/" + deviceCode);
        if (StrUtils.isNotNull(result) && !result.equals("error")) {
            EquipmentInfoDto equipmentInfoDto = JSON.parseObject(result,EquipmentInfoDto.class);
            DbHillstoneDevice device = equipmentInfoDto.formartHillstoneDevice();
            return device;
        }
        return null;
    }
}
